const Router = require('koa-router')
const koaBody = require('koa-body')
const _ = require('lodash')
const utils = require('./utils')
const { error, INFO } = require('./utils/error')
const apiError = (info) => {
  error('50000', __filename, info)
}
const {
  requestRank,
  requestRecommend,
  requestComment,
  requestNews,
  requestAddNews,
  requestComplain,
  requestReNews,
  requestEditReNews,
  requestAddComment
} = require('./api/news')
const router = new Router({
  prefix: '/api/news'
})

router.get('/rank', async (ctx) => {
  const rankMap = (data) =>
    data.map((item) => {
      return {
        id: item.id,
        title: item.title,
        number: item.number
      }
    })
  const result = {
    month: {
      browse: [],
      comments: []
    },
    week: {
      browse: [],
      comments: []
    },
    day: {
      browse: [],
      comments: []
    }
  }
  let code = -1
  let msg = ''
  try {
    const { status, data } = await requestRank()
    if (status === 200) {
      if (data.statu === 0) {
        code = 1
        result.month.browse = rankMap(data.data.month.browse)
        result.month.comments = rankMap(data.data.month.comments)
        result.week.browse = rankMap(data.data.week.browse)
        result.week.comments = rankMap(data.data.week.comments)
        result.day.browse = rankMap(data.data.day.browse)
        result.day.comments = rankMap(data.data.day.comments)
      } else {
        msg = data.msg
      }
    }
  } catch {
    apiError('GET-rank')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      data: result,
      msg
    }
  }
})

router.get('/', async (ctx) => {
  const { id } = ctx.query
  let userId = -1
  let code = -1
  let result
  let msg = ''
  if (ctx.isAuthenticated()) {
    userId = ctx.session.passport.user.id
  }
  try {
    const { status, data } = await requestNews({
      id,
      userId
    })
    if (status === 200 && data.statu === 0) {
      code = 1
      const item = data.data
      const content = item.content.replace(
        utils.ipRegex,
        utils.settings.URL__STATIC
      )
      // const content = `# ${item.title}\n> 发布时间：${item.date}\n> 作者：[${item.authorName}](/user/${item.authorId}/attention)\n> 浏览数：${item.browse}\n> 评论数：${item.comments}\n\n${item.content}`.replace(
      //   utils.ipRegex,
      //   utils.settings.URL__STATIC
      // )
      result = {
        id: item.id,
        title: item.title,
        author: {
          id: item.authorId,
          name: item.authorName
        },
        classId: item.plateId,
        mapId: item.classId,
        time: item.date,
        browse: item.browse,
        comments: item.comments,
        content
      }
    }
  } catch (error) {
    apiError('GET-/')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      data: result,
      msg
    }
  }
})
router.post('/', async (ctx) => {
  const body = ctx.request.body
  let code = -1
  let msg = ''
  try {
    const { status, data } = await requestAddNews({
      title: body.title,
      classId: body.classId,
      content: body.content,
      img: body.titleImg,
      userId: ctx.session.passport.user.id
    })
    if (status === 200) {
      if (data.statu === 0) {
        code = 0
      } else {
        msg = data.msg
      }
    }
  } catch {
    apiError('POST-/')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      msg
    }
  }
})
router.get('/re', async (ctx) => {
  const { id } = ctx.query
  let code = -1
  let result
  let msg = ''
  try {
    const { status, data } = await requestReNews({
      id,
      userId: ctx.session.passport.user.id
    })
    if (status === 200 && data.statu === 0) {
      code = 1
      const item = data.data
      result = {
        id: item.id,
        title: item.title,
        titleImg: item.img,
        class: [item.plateId, item.classId],
        content: item.content
      }
    }
  } catch {
    apiError('GET-/re')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      data: result,
      msg
    }
  }
})
router.post('/re', async (ctx) => {
  const body = ctx.request.body
  let code = -1
  let msg = ''
  try {
    const { status, data } = await requestEditReNews({
      id: body.id,
      userId: body.userId,
      cid: body.replyId,
      content: body.content
    })
    if (status === 200) {
      if (data.statu === 0) {
        code = 0
      } else {
        msg = data.msg
      }
    }
  } catch {
    apiError('POST-re')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      msg
    }
  }
})

router.post(
  '/img',
  koaBody({
    multipart: true
  }),
  (ctx) => {
    const fileImg = []
    let code = -1
    let msg = ''
    const files = ctx.request.files
    _.forIn(files, function(value) {
      if (utils.changeSize(value.size, 'm') > 2) {
        msg = '有图片大小大于2M'
      }
    })
    if (msg === '') {
      code = 1
      _.forIn(files, function(value, key) {
        fileImg.push([key, utils.upNewsImg(value)])
      })
    }
    ctx.body = {
      code,
      msg,
      fileImg
    }
  }
)
router.get('/recommend', async (ctx) => {
  const { id } = ctx.query
  let result
  let code = -1
  let msg = ''
  try {
    const { status, data } = await requestRecommend({
      id
    })
    if (status === 200 && data.statu === 0) {
      code = 1
      result = data.data.map((item) => {
        return {
          id: item.id,
          title: item.title,
          imgUrl: item.img
        }
      })
    }
  } catch {
    apiError('GET-recommend')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      data: result,
      msg
    }
  }
})

router.get('/comment', async (ctx) => {
  const { id } = ctx.query
  let result
  let code = -1
  let msg = ''
  try {
    const { status, data } = await requestComment({
      id
    })
    if (status === 200 && data.statu === 0) {
      code = 1
      result = data.data.map((item) => {
        return {
          id: item.id,
          user: {
            id: item.user.id,
            name: item.user.name,
            avatar: item.user.img
          },
          time: item.date,
          content: item.content,
          reply: item.reply.map((itemReply) => {
            return {
              id: itemReply.id,
              user: {
                id: itemReply.user.id,
                name: itemReply.user.name,
                avatar: itemReply.user.img
              },
              replyUser: {
                id: itemReply.replyUser.id,
                name: itemReply.replyUser.name
              },
              time: itemReply.date,
              content: itemReply.content
            }
          })
        }
      })
    }
  } catch (error) {
    apiError('GET-comment')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      data: result,
      msg
    }
  }
})

router.post('/comment', async (ctx) => {
  const body = ctx.request.body
  let msg = ''
  let code = -1
  let result = ''
  try {
    const { status, data } = await requestAddComment({
      id: body.id,
      userId: ctx.session.passport.user.id,
      cid: body.replyId,
      content: body.content
    })
    if (status === 200) {
      if (data.statu === 0) {
        code = 0
        result = {
          time: data.data.time
        }
      } else {
        msg = data.msg
      }
    }
  } catch (error) {
    apiError('POST-comment')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      data: result,
      msg
    }
  }
})
router.post('/complain', async (ctx) => {
  const { id, content } = ctx.request.body
  let msg = ''
  let code = -1
  try {
    const { status, data } = await requestComplain({
      id,
      content,
      userId: ctx.session.passport.user.id
    })
    if (status === 200) {
      if (data.statu === 0) {
        code = 0
      } else {
        msg = data.msg
      }
    }
  } catch (error) {
    apiError('GET-complain')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      msg
    }
  }
})
module.exports = router
